package com.horay.springbootdemo.filter.interceptor.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * StopWatchFilter
 *
 * @author heyingcheng
 * @date 2019/9/2 1:21
 */
@Slf4j
@Component
@WebFilter(filterName = "StopWatchFilter", urlPatterns = "/*")
public class StopWatchFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("StopWatchFilter.init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("StopWatchFilter.doFilter");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        filterChain.doFilter(servletRequest, servletResponse);
        stopWatch.stop();
        log.info("time:[{}]", stopWatch.getTotalTimeMillis());
    }

    @Override
    public void destroy() {
        log.info("StopWatchFilter.destroy");
    }

}